package com.hjm.admin.moule.view.fragment.impl;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;

import com.allen.library.utils.ToastUtils;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.hjm.admin.moule.R;
import com.hjm.admin.moule.db.entity.CollBookBean;
import com.hjm.admin.moule.db.helpter.CollBookHelper;
import com.hjm.admin.moule.utils.Constant;
import com.hjm.admin.moule.utils.StringUtils;
import com.hjm.admin.moule.view.activity.impl.MainActivity;
import com.hjm.admin.moule.view.base.BaseFileFragment;
import com.hjm.admin.moule.view.base.BaseFragment;
import com.hjm.admin.moule.view.base.BaseViewPageAdapter;
import com.hjm.admin.moule.viewmodel.BaseViewModel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class ScanBookFragment extends BaseFragment {
    @BindView(R.id.nts_scan)
    NavigationTabStrip mNtsScan;
    @BindView(R.id.vp_scan)
    ViewPager mVpScan;
    @BindView(R.id.file_system_cb_selected_all)
    CheckBox mCbSelectAll;
    @BindView(R.id.file_system_btn_add_book)
    Button mBtnAddBook;
    @BindView(R.id.file_system_btn_delete)
    Button mBtnDelete;
    String titles[] = {"只能导入", "手机目录"};
    private List<Fragment> mFragments;
    private BaseFileFragment mCurFragment;
    private LocalBookFragment mLocalBookFragment;
    private BaseFileFragment.OnFileCheckedListener mListener = new BaseFileFragment.OnFileCheckedListener() {
        @Override
        public void onItemCheckedChange(boolean isChecked) {
            changeMenuStatus();
        }

        @Override
        public void onCategoryChanged() {
            mCurFragment.setCheckedAll(false);
            changeMenuStatus();
            changeCheckedAllStatus();
        }
    };
    private FileCategoryFragment mCategoryFragment;

    public static ScanBookFragment newInstance() {
        return new ScanBookFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return setContentView(container, R.layout.fragment_scan_book, new BaseViewModel(mContext));
    }

    @Override
    protected void initView() {
        mFragments = new ArrayList<>();
        mLocalBookFragment = LocalBookFragment.newInstance();
        mCategoryFragment = FileCategoryFragment.newInstance();
        mCurFragment = mLocalBookFragment;
        mFragments.add(mLocalBookFragment);
        mFragments.add(mCategoryFragment);

        mVpScan.setAdapter(new BaseViewPageAdapter(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), titles, mFragments));
        mVpScan.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ((MainActivity) getActivity()).setLeftSlide(position == 0);
                if (position == 0) {
                    mCurFragment = mLocalBookFragment;
                } else {
                    mCurFragment = mCategoryFragment;
                }
                changeMenuStatus();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mNtsScan.setTitles(titles);
        mNtsScan.setViewPager(mVpScan);
        mLocalBookFragment.setOnFileCheckedListener(mListener);
    }

    @OnClick({R.id.file_system_cb_selected_all, R.id.file_system_btn_add_book, R.id.file_system_btn_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.file_system_cb_selected_all:
                mCurFragment.setCheckedAll(mCbSelectAll.isChecked());
                changeMenuStatus();
                break;
            case R.id.file_system_btn_add_book:
                List<File> files = mCurFragment.getCheckedFiles();
                List<CollBookBean> collBooks = convertCollBook(files);
                CollBookHelper.getsInstance().saveBooks(collBooks);
                mCurFragment.setCheckedAll(false);
                changeMenuStatus();
                changeCheckedAllStatus();
                ToastUtils.showToast(getResources().getString(R.string.wy_file_add_succeed, collBooks.size()));
                break;
            case R.id.file_system_btn_delete:
                new AlertDialog.Builder(mContext)
                        .setTitle("删除文件")
                        .setMessage("确定删除文件吗？")
                        .setPositiveButton(getResources().getString(R.string.wy_common_sure), (dialog, whitch) -> {
                            mCurFragment.deleteCheckedFiles();
                            ToastUtils.showToast("删除文件成功");
                        })
                        .setNegativeButton(getResources().getString(R.string.wy_common_cancel), null)
                        .show();
                break;
        }
    }

    private List<CollBookBean> convertCollBook(List<File> files) {
        List<CollBookBean> collBooks = new ArrayList<>(files.size());
        for (File file : files) {
            if (!file.exists()) continue;
            CollBookBean collBookBean = new CollBookBean();
            collBookBean.setIsLocal(true);
            collBookBean.set_id(file.getAbsolutePath());
            collBookBean.setTitle(file.getName().replace(".txt", ""));
            collBookBean.setLastChapter("开始阅读");
            collBookBean.setLastRead(StringUtils.dateConvert(System.currentTimeMillis(), Constant.FORMAT_BOOK_DATE));
            collBooks.add(collBookBean);
        }

        return collBooks;
    }

    private void changeCheckedAllStatus() {
        int count = mCurFragment.getCheckedCount();
        if (count > 0) {
            mCbSelectAll.setClickable(true);
            mCbSelectAll.setEnabled(true);
        } else {
            mCbSelectAll.setClickable(false);
            mCbSelectAll.setEnabled(false);
        }
    }

    private void changeMenuStatus() {
        if (mCurFragment.getCheckableCount() == 0) {
            mBtnAddBook.setText(getString(R.string.wy_file_add_shelf));
            setMenuClickable(false);
            if (mCbSelectAll.isChecked()) {
                mCurFragment.setChecked(false);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }
        } else {
            mBtnAddBook.setText(getString(R.string.wy_file_add_shelves, mCurFragment.getCheckableCount()));
            setMenuClickable(true);
            if (mCurFragment.getCheckableCount() == mCurFragment.getCheckableCount()) {
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            } else if (mCurFragment.isCheckedAll()) {
                mCurFragment.setChecked(false);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }
        }
        if (mCurFragment.isCheckedAll())
            mCbSelectAll.setText("取消");
        else
            mCbSelectAll.setText("全选");
    }

    private void setMenuClickable(boolean isClickable) {
        mBtnDelete.setEnabled(isClickable);
        mBtnDelete.setClickable(isClickable);
        mBtnAddBook.setEnabled(isClickable);
        mBtnAddBook.setClickable(isClickable);
    }
}
